//
//  LQKeyChain.m
//  LQProductIntelligenceService
//
//  Created by Yim on 16/6/30.
//  Copyright © 2016年 张宁. All rights reserved.
//

#import "LQKeyChain.h"
#import <Security/Security.h>

@implementation LQKeyChain

+ (NSMutableDictionary *)getKeychainQuery:(NSString *)key {
    
    return [NSMutableDictionary dictionaryWithObjectsAndKeys:(__bridge id)kSecClassGenericPassword, (__bridge id)kSecClass,
            
            key, (__bridge id)kSecAttrService, key, (__bridge id)kSecAttrAccount, (__bridge id)kSecAttrAccessibleAfterFirstUnlock,(__bridge id)kSecAttrAccessible, nil];
}

+ (void)save:(NSString *)key data:(id)data {
    
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:key];
    
    SecItemDelete((__bridge CFDictionaryRef)keychainQuery);
    
    [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(__bridge id)kSecValueData];
    
    SecItemAdd((__bridge CFDictionaryRef)keychainQuery, NULL);
}

+ (id)load:(NSString *)key {
    
    id ret = nil;
    
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:key];
    
    [keychainQuery setObject:(id)kCFBooleanTrue forKey:(__bridge id)kSecReturnData];
    
    [keychainQuery setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];
    
    CFDataRef keyData = NULL;
    
    if (SecItemCopyMatching((__bridge CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {
        
        @try {
            
            ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData];
            
        } @catch (NSException *e) {
            
            //            NSLog(@"Unarchive of %@ failed: %@", key, e);
            
        } @finally {
            
        }
        
    }
    
    if (keyData) {
        
        CFRelease(keyData);
        
    }
    
    return ret;
    
}

+ (void)remove:(NSString *)key {
    
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:key];
    
    SecItemDelete((__bridge CFDictionaryRef)keychainQuery);
    
}


@end
